/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 * */

// AmzServer - Tototoy's server model.
// Author: tonyjobmails@gmail.com (tonyhack).
//
// Test of RingQueueSingleModelBoundless.
//

#include <string>
#include <iostream>

#include "common.h"
#include "ring_queue_single_model_boundless.h"

using namespace amz;

RingQueueInterface *ring_queue = NULL;

bool Write(uint32 loop, const char *data, uint32 len) {
  while(loop--) {
    if(ring_queue->Add(data, len) <= 0) {
      LOG(INFO) << "Write error loop = " << loop + 1;
      return false;
    }

    LOG(INFO) << "Write data=\"" << data << "\"";
    // ((RingQueueSingleModelBoundless *)ring_queue)->LogPrint();
  }

  return true;
}

bool Read(uint32 loop) {
  while(loop--) {
    char buffer[ring_queue_define::kDefaultBufferSingleUnitSize];
    int32 len = ring_queue->Remove(buffer, ring_queue_define::kDefaultBufferSingleUnitSize);
    if(len <= 0) {
      LOG(INFO) << "Read error loop = " << loop + 1;
      return false;
    }

    buffer[len] = '\0';
    LOG(INFO) << "Read data=\"" << buffer << "\"";
    // ((RingQueueSingleModelBoundless *)ring_queue)->LogPrint();
  }

  return true;
}

int main() {
  // InitializeLogger("/tmp/info.log", "/tmp/warn.log", "/tmp/erro.log");
  ring_queue = new RingQueueSingleModelBoundless(64, 32, false);
  std::string data1, data2, data3, data4, data5, data6;
  data1 = "1111";
  data2 = "2222222222222";
  data3 = "333333333333333";
  data4 = "444444444444";
  data5 = "555555";
  data6 = "666666666666666666";
  Write(1, data1.c_str(), data1.length());

  Write(4, data2.c_str(), data2.length());
  Read(2);

  Write(5, data3.c_str(), data3.length());
  Read(5);
  ring_queue->Flush();
  LOG(INFO) << "Flush data";
  Read(4);
  Write(3, data4.c_str(), data4.length());
  Read(4);
  ring_queue->Flush();
  LOG(INFO) << "Flush data";
  Read(4);
  Write(5, data5.c_str(), data5.length());
  Read(4);
  Write(6, data6.c_str(), data6.length());
  Read(4);
  ring_queue->Flush();
  LOG(INFO) << "Flush data";
  Read(4);
  ring_queue->Flush();
  LOG(INFO) << "Flush data";
  Read(4);
  ring_queue->Flush();
  LOG(INFO) << "Flush data";
  Read(4);

  return 0;
}
